package com.itcm.skymail.product.config;

import com.alibaba.fastjson.support.spring.GenericFastJsonRedisSerializer;
import org.springframework.boot.autoconfigure.cache.CacheProperties;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.cache.RedisCacheConfiguration;
import org.springframework.data.redis.serializer.RedisSerializationContext;
import org.springframework.data.redis.serializer.StringRedisSerializer;

/**
 * 描述:
 *
 * @author cm_fighting
 * @create 2020-10-21 9:59 上午
 */
@EnableCaching
@Configuration
@EnableConfigurationProperties(CacheProperties.class)
public class MyRedisCacheConfig {

    /**
     * 让配置文件中的配置生效
     * 1. 下面参考源码的写法中  读到配置文件中的配置 就设置到config中
     * <p>
     * 2. 源码中和这个配置文件绑到的配置类的写法是这样的
     *
     * @ConfigurationProperties(prefix = "spring.cache")
     * public class CacheProperties
     * 它并没有注入到容器中
     * 想让他生效，开启属性配置绑定 @EnableConfigurationProperties
     * 然后  可以@Autowired 注入CacheProperties
     * 也可以直接使用 ，通过传参传入，这也是源码中默认配置的写法
     * CacheProperties.Redis redisProperties = cacheProperties.getRedis();
     */

    @Bean
    RedisCacheConfiguration configuration(CacheProperties cacheProperties) {

        // 在默认的基础上改
        RedisCacheConfiguration config = RedisCacheConfiguration.defaultCacheConfig();

        // 修改k v 的序列化规则
        config = config.serializeKeysWith(RedisSerializationContext.SerializationPair.fromSerializer(new StringRedisSerializer()));
        config = config.serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(new GenericFastJsonRedisSerializer()));
        // 将我们配置文件中 ：application.properties所有配置生效
        // 源码中默认配置的写法
        CacheProperties.Redis redisProperties = cacheProperties.getRedis();
        if (redisProperties.getTimeToLive() != null) {
            config = config.entryTtl(redisProperties.getTimeToLive());
        }
        if (redisProperties.getKeyPrefix() != null) {
            config = config.prefixCacheNameWith(redisProperties.getKeyPrefix());
        }
        if (!redisProperties.isCacheNullValues()) {
            config = config.disableCachingNullValues();
        }
        if (!redisProperties.isUseKeyPrefix()) {
            config = config.disableKeyPrefix();
        }
        return config;
    }
}
